import PropTypes from 'prop-types'
import React, { memo, useEffect, useRef } from 'react'
import { IndicatorWrapper } from './style'

const Indicator = memo((props) => {
  const { selectIndex } = props;

  const IndicatorContentRef = useRef();
  useEffect(()=>{
    const currDom = IndicatorContentRef.current.children[selectIndex]
    const contentWidth = IndicatorContentRef.current.clientWidth
    const contentScrollWidth = IndicatorContentRef.current.scrollWidth;
    const currDomWidth = currDom.clientWidth
    const currDomOffsetL = currDom.offsetLeft
    
    let distance = currDomOffsetL - .5 * contentWidth + .5 * currDomWidth
    distance = distance<0?0:distance // 左边处理
    if (contentScrollWidth - contentWidth < distance){ // 右边处理
      distance = contentScrollWidth - contentWidth 
    }
    IndicatorContentRef.current.style.transform = `translate(${-distance}px)`
  }, [selectIndex])

  return (
    <IndicatorWrapper>
      <div className="i-content" ref={ IndicatorContentRef }>
        {props.children}
      </div>
    </IndicatorWrapper>
  )
})

Indicator.propTypes = {
  selectIndex: PropTypes.number
}

export default Indicator